package chen.web.back.client.system;

import java.util.ArrayList;
import java.util.List;

import chen.web.back.client.FormDataBuilder;
import chen.web.back.client.UrlHelper;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.CheckColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.tips.QuickTip;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Element;

public class CachePanel extends LayoutContainer {

	@Override
	protected void onRender(Element parent, int index) {
		// TODO Auto-generated method stub
		super.onRender(parent, index);
		VerticalPanel vp = new VerticalPanel();
		loadCacheInfo();
		vp.add(createTablePanel());
		add(vp);
	}
	
	private static class CacheInfo extends BaseModelData {
		
		  public String getName() {
		    return get("name");
		  }

		  public void setName(String name) {
		    set("name", name);
		  }
		  
		  public String getDescription(){
			  return get("description");
		  }
		  
		  public void setDescription(String description){
			  set("description", description);
		  }
		  
		  public void setSize(int size){
			  set("size", size);
		  }
		  public int getSize(){
			  return get("size");
		  }
		  
		  public void setMisses(long misses){
			  set("misses", misses);
		  }
		  public long getMisses(){
			  return get("misses");
		  }
		  
		  public void setHits(long hits){
			  set("hits", hits);
		  }
		  public long getHits(){
			  return get("hits");
		  }
		  
		  //命中率
		  public void setPoh(String poh){
			set("poh", poh);  
		  }
		  public String getPoh(){
			  return get("poh");
		  }

		}
	
	private ListStore<CacheInfo> store = new ListStore<CacheInfo>();
	private void loadCacheInfo(){
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, UrlHelper.toAbsolute("/cache"));
		try{
			builder.sendRequest(null, new RequestCallback(){

				@Override
				public void onError(Request arg0, Throwable arg1) {
					// TODO Auto-generated method stub
					displayError("Couldn't retrieve JSON");
				}

				@Override
				public void onResponseReceived(Request arg0, Response response) {
					// TODO Auto-generated method stub
					if (200 == response.getStatusCode()) {
						JSONValue json = JSONParser.parseStrict(response
								.getText()).isObject().get("returnObject");
						JSONArray array = json.isArray();
						for(int i=0; i<array.size(); i++){
							JSONObject infoObj = array.get(i).isObject();
							String name = infoObj.get("name").isString().stringValue();
							String description = infoObj.get("description").isString().stringValue();
							double size = infoObj.get("size").isNumber().doubleValue();
							double misses = infoObj.get("misses").isNumber().doubleValue();
							double hits = infoObj.get("hits").isNumber().doubleValue();
	
							CacheInfo info = new CacheInfo();
							info.setName(name);
							info.setDescription(description);
							info.setSize((int)size);
							info.setMisses((long)misses);
							info.setHits((long)hits);
							info.setPoh((long)hits + "/" + ((long)misses + (long)hits));
							store.insert(info, i);
						}
					} else {
						displayError("Couldn't retrieve JSON ("
								+ response.getStatusText() + ")");
					}
				}
				
			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			displayError("Couldn't retrieve JSON");
		}
	}
	
	private void clearCache(String name){
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, UrlHelper.toAbsolute("/cache/clear"));
		builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
		try{
			FormDataBuilder fdb = new FormDataBuilder();
			fdb.addProperty("name", name);
			builder.sendRequest(fdb.toQueryString(), new RequestCallback(){

				@Override
				public void onError(Request arg0, Throwable arg1) {
					// TODO Auto-generated method stub
					displayError("Couldn't retrieve JSON");
				}

				@Override
				public void onResponseReceived(Request arg0, Response response) {
					// TODO Auto-generated method stub
					if (200 == response.getStatusCode()) {
						boolean success = JSONParser.parseStrict(response
								.getText()).isObject().get("success").isBoolean().booleanValue();
						if(!success){
							displayError("操作失败");
						}else{
							MessageBox.alert("成功", "操作成功", null);
						}
					} else {
						displayError("Couldn't retrieve JSON ("
								+ response.getStatusText() + ")");
					}
				}
				
			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			displayError("Couldn't retrieve JSON");
		}
	}
	
	private ContentPanel createTablePanel(){ 
	    List<ColumnConfig> columns = new ArrayList<ColumnConfig>();  
	    
	    final CheckBoxSelectionModel<CacheInfo> sm = new CheckBoxSelectionModel<CacheInfo>();  
	    columns.add(sm.getColumn());
	    columns.add(new ColumnConfig("name", "名称", 150));  
	    columns.add(new ColumnConfig("description", "描述", 375));   
	    columns.add(new ColumnConfig("size", "大小", 50));  
	    columns.add(new ColumnConfig("poh", "命中率", 70));
	    
		ColumnModel cm = new ColumnModel(columns);  
		
		cp = new ContentPanel();  
	    cp.setHeading("缓存列表");  
	    cp.setFrame(true);  
	    cp.setWidth(700);  
	    cp.setLayout(new FitLayout());  

	    grid = new EditorGrid<CacheInfo>(store, cm);
	    grid.setSelectionModel(sm);  
	    grid.setBorders(true);  
	    grid.setColumnReordering(true);  
	    grid.getAriaSupport().setLabelledBy(cp.getHeader().getId() + "-label");  
	    grid.addPlugin(sm);  
	    
	    cp.add(grid);
	    
	    cp.setButtonAlign(HorizontalAlignment.CENTER);
	    cp.addButton(new Button("清除缓存", new SelectionListener<ButtonEvent>() {
	      @Override
	      public void componentSelected(ButtonEvent ce) {
	    	  List<CacheInfo> list = sm.getSelectedItems();
	    	  for(CacheInfo info : list){
	    		  clearCache(info.getName());
	    	  }
	      }
	    }));
	    cp.addButton(new Button("刷新", new SelectionListener<ButtonEvent>() {
		      @Override
		      public void componentSelected(ButtonEvent ce) {
		    	  store.removeAll();
		    	  loadCacheInfo();
		      }
		}));
	    
	    grid.addListener(Events.ViewReady, new Listener<ComponentEvent>() {
	        public void handleEvent(ComponentEvent be) {
	            grid.getStore().addListener(Store.Add, new Listener<StoreEvent<CacheInfo>>() {
	                public void handleEvent(StoreEvent<CacheInfo> be) {
	                  doAutoHeight();
	                }
	              });
	              doAutoHeight();
	        }
	    });
	    
	    return cp;
	}
	  private EditorGrid<CacheInfo> grid;
	  private ContentPanel cp;
	  protected void doAutoHeight() {
		    if (grid.isViewReady()) {
		      grid.getView().getScroller().setStyleAttribute("overflowY", "hidden");
		      cp.setHeight((grid.getView().getBody().isScrollableX() ? 19 : 0) + grid.el().getFrameWidth("tb")
		          + grid.getView().getHeader().getHeight() + cp.getFrameHeight()
		          + grid.getView().getBody().firstChild().getHeight());
		    }
	  }
	
	
	  
	private void displayError(String message){
		MessageBox.alert("出错", message, null);
	}
	
}
